<?php

namespace app\admin\controller;

use think\captcha\facade\Captcha;
use think\Request;
use think\facade\Validate;
use app\admin\model\User as UserModel;

/**
 * 登录相关
 */
class Login extends Base
{
    /**
     * @param Request $request
     * @return \think\Response
     */
    public function index(Request $request)
    {
        $data = $request->param();
        $user = UserModel::field('id,password')
                            ->where(['username' => $data['username']])
                            ->find();

        //验证用户名和密码规则
        $result = Validate::rule([
            'username' => 'unique:user,username^password'
        ])->check([
            'username' => $data['username'],
            'password' => sha1($data['password'])
        ]);
        //生成随机 token ，然后md5加密
        $token = md5(md5(rand(0000,9999).chr(rand(65,90)).chr(rand(97,122)).chr(rand(65,90))
            .$user['id'].rand(0000,9999)
            .$user['password'].chr(rand(97,122)).chr(rand(65,90)).chr(rand(97,122)).time().rand(0000,9999)));

        $userInfo = UserModel::field('id,username,gender,email')->find($user['id']);

        $usercc = [
            "token"     => $token,
            'userInfo'  => $userInfo
        ];


        if (!captcha_check($data['code'])) {
            return $this->create([], '请重新输入验证码', 400);
        }
        //判断，反向的
        if (!$result) {
            session('admin', $data['username']);
            return $this->create($usercc, '登录成功~', 200);
        } else {
            return $this->create([], '用户名或密码不正确~', 400);
        }
    }


    /**
     * 获取验证码
     * @return \think\Response
     */
    public function verify($config = null)
    {
        return Captcha::create($config);
    }


    public function login_ed()
    {
        return View();
    }

}